﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Ferreteria.Forms.Informes
{
    public partial class FrmExportListPrecios : Form
    {

        DisancoEntities context;
        PictureBox logo;
        DataTable dtArticulos;
        string namefile;

        public FrmExportListPrecios()
        {
            InitializeComponent();
            cmbRubro.Enabled = false;
            cmbCategorias.Enabled = false;
            context = new DisancoEntities(Ferreteria.Clases.Constantes.cadenaConexion);
            cmbRubro.DataSource = context.Rubros;
            cmbRubro.ValueMember = "rubro_id";
            cmbRubro.DisplayMember = "rubro_nombre";
            btnGenerar.Enabled = false;
            btnExportarExcel.Enabled = false;
            

            logo = new PictureBox();
            //logo.Image = Logo.Image;
            context = null;
        }

        private void btnSalir_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void cmbRubro_SelectedIndexChanged(object sender, EventArgs e)
        {
            cmbCategorias.DataSource = ((Rubros)cmbRubro.SelectedItem).Categorias;
            cmbCategorias.ValueMember = "categ_id";
            cmbCategorias.DisplayMember = "categ_nombre";
        }


        private void chkRubro_CheckedChanged(object sender, EventArgs e)
        {
            if (chkRubro.Checked)
            {
                cmbRubro.Enabled = true;
                btnGenerar.Enabled = true;
            }
            else if (!chkRubro.Checked)
            {
                cmbRubro.Enabled = false;
                btnGenerar.Enabled = true;
            }
        }

        private void chkCateg_CheckedChanged(object sender, EventArgs e)
        {
            if (chkCateg.Checked)
            {
                cmbCategorias.Enabled = true;
               
            }
            else if (!chkCateg.Checked)
            {
                cmbCategorias.Enabled = false;
            }
        }

        private void btnGenerar_Click(object sender, EventArgs e)
        {
            context = new DisancoEntities(Ferreteria.Clases.Constantes.cadenaConexion);

            dtArticulos = new DataTable();
            dtArticulos.Columns.Add("id");
            dtArticulos.Columns.Add("Codigo");
            dtArticulos.Columns.Add("Articulo");
            dtArticulos.Columns.Add("Precio");
            dtArticulos.Rows.Clear();

            if (chkRubro.Checked)
            {
                int RubroID = Convert.ToInt32(cmbRubro.SelectedValue.ToString());

                var ArtQuery = from art in context.Articulos
                               where art.Categorias.Rubros.rubro_id == RubroID
                               select art;
                namefile = cmbRubro.Text;

                if (chkCateg.Checked)//Si  esta marcada busco por Categoria
                {
                    int CategID = Convert.ToInt32(cmbCategorias.SelectedValue.ToString());


                    ArtQuery = from art in context.Articulos

                               where art.Categorias.categ_id == CategID
                               where art.Categorias.Rubros.rubro_id == RubroID
                               select art;

                    //Filtro = "Filtrado por: Articulos del Rubro " + cmbRubro.Text + " y Categoria " + cmbCategorias.Text;
                    
                    namefile = cmbCategorias.Text;
                }


                foreach (var listaart in ArtQuery)
                {
                    DataRow fila = dtArticulos.NewRow();
                    fila["Codigo"] = listaart.art_codigo;
                    fila["Articulo"] = listaart.art_nombre;
                    fila["Precio"] = "$ " + listaart.art_precio_oferta;
                    fila["id"] = listaart.art_id;
                    dtArticulos.Rows.Add(fila);
                }
                datagridviewListaprecios.DataSource = dtArticulos;
                datagridviewListaprecios.Columns[0].Visible = false;
                datagridviewListaprecios.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
                datagridviewListaprecios.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                datagridviewListaprecios.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                btnExportarExcel.Enabled = true;

            }
        }

        private void btnExportarExcel_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("¿Desea Exportar a Excel?", "Confirme la operación", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (dr == System.Windows.Forms.DialogResult.Yes)
            {
                exportListaPreciosaExcel(datagridviewListaprecios);
                Limpiar();
                //this.Close();
            }
            
        }

        private void Limpiar()
        {
            dtArticulos.Clear();
            
        }

       
        private void exportListaPreciosaExcel(DataGridView datagridviewListaprecios)
        {
   
            Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();

            Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);

            Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
            app.Visible = true;

            app.SheetsInNewWorkbook = 1;
            worksheet = workbook.ActiveSheet;
        
            string name = "Export de Precios";
            worksheet.Name = name;

            DataGridView dgvExport = datagridviewListaprecios;

            // storing header part in Excel 

            for (int i = 2; i < dgvExport.Columns.Count + 1; i++)
            {
                worksheet.Cells[1, i] = dgvExport.Columns[i - 1].HeaderText;
            }

            // storing Each row and column value to excel sheet 
            int columnas = dgvExport.Columns.Count;
            int filas = dgvExport.Rows.Count;

            for (int i = 0; i < filas; i++)
            {
                for (int j = 1; j < columnas; j++)
                {
                    worksheet.Cells[i + 2, j + 1] = dgvExport.Rows[i].Cells[j].Value.ToString();
                }
            }
            //save the application 
            
            string datefile = Convert.ToString(DateTime.Today.Day.ToString());
            string monthfile = (DateTime.Today.Month.ToString());
            string yearfil = Convert.ToString(DateTime.Today.Year.ToString());
            string file = ("Export" + namefile + datefile + monthfile + yearfil + ".xls");
            workbook.SaveAs(file, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
            Type.Missing);
           
            app.Quit();

        }
    }
}
